let user = null;
let question = null;
let author = null;
let userArray = [];
let answerTemplate = "";
let vditor = null;
let answerArray = [];

// 函数：根据 id 获取 username
function getUsernameById(id) {
    const user = userArray.find(user => user.id === id);
    return user ? user.username : "未知用户";
}

async function initAuthor(authorId) {
     await fetch(`/api/user/${authorId}`)
        .then(response => {
            if (!response.ok) {
                parent.layui.layer.alert(`获取作者信息出错！<br />状态码：${response.status}`);
                return false;
            }
            return response.json();
        })
        .then(data => {
            document.getElementById("question-author").innerText = data.username;
            return true;
        })
        .catch(error => {
            parent.layui.layer.msg("因网络原因，获取作者信息失败");
            return false;
        });
}

async function initUserArray() {
    return await fetch('/api/user')
        .then(response => {
            if (!response.ok) {
                parent.layui.layer.alert(`获取用户列表出错！<br />状态码：${response.status}`);
                return false;
            }
            return response.json();
        })
        .then(data => {
            userArray = data;
            return true;
        })
        .catch(error => {
            parent.layui.layer.msg("因网络原因，获取用户列表失败");
            return false;
        });
}

async function initQuestion() {
    let questionId = getQueryVariable("id");
    let mainElement = document.querySelector("#main");
    if (questionId === null) {
        mainElement.innerHTML = `<h3>请选择一个问题查看回答</h3>`;
        return;
    }

    return await fetch(`/api/question/${questionId}`)
        .then(response => {
            if (!response.ok) {
                parent.layui.layer.alert(`获取问题出错！<br />状态码：${response.status}`);
                mainElement.innerText = `获取问题出错！<br />状态码：${response.status}`;
                return true;
            }
            return response.json();
        })
        .then(data => {
            question = data;
            document.getElementById("title").innerText = data.title;
            document.title = data.title;
            document.getElementById("content").innerHTML = marked.parse(data.content);
            document.getElementById("question-time").innerText =
                `发布于:${data.createdAt.replace("T", " ")}`;
            if (data.createdAt !== data.updatedAt) {
                document.getElementById("question-time").innerText +=
                    `　编辑于:${data.updatedAt.replace("T", " ")}`;
            }
            initAuthor(data.userId);
            return false;
        })
        .catch(error => {
            parent.layui.layer.msg('因网络原因，获取问题失败！');
            mainElement.innerText = '因网络原因，获取问题失败！';
            console.error('Error:', error);
            return false;
        });
}

async function initAnswer(questionId) {
    await initUserArray();
    if (userArray.length === 0) {
        return;
    }
    await fetch(`/api/answer/question-id/${questionId}`)
        .then(response => {
            if (!response.ok) {
                parent.layui.layer.alert(`获取回答出错！<br />状态码：${response.status}`);
                return [];
            }
            return response.json();
        })
        .then(data => {
            answerArray = data;
            layui.laytpl(answerTemplate).render(data, function (html) {
                document.getElementById("answer-list").innerHTML = html;
            });
        })
        .catch(error => {
            parent.layui.layer.msg('因网络原因，获取回答失败！');
            console.error('Error:', error);
        });
    hljs.highlightAll();
}

async function initUser() {
    return await fetch('/api/auth/user')
        .then(response => {

            if (!response.ok && (response.status < 400 && response.status >= 500)) {
                parent.layui.layer.alert(`获取当前用户信息出错！<br />状态码：${response.status}`);
                return false;
            }

            if (!response.ok) {
                parent.layui.layer.msg(`当前您未登录！`);
                return false;
            }
            response.json().then(data => {
                user = data;
            });
            return true;
        })
        .catch(error => {
            parent.layui.layer.msg('因网络原因，获取用户信息失败！');
            console.error('Error:', error);
            return false;
        });
}

function initAnswerAdd() {
    let answerAddElement = document.getElementById("answer-add");
    answerAddElement.addEventListener('click', async function () {
        if (!user) {
            parent.layui.layer.alert(`当前您未登录，登陆后才能发表回答！`);
            return;
        }
        if (user.role !== "RESPONDER" && user.role !== "ADMIN") {
            parent.layui.layer.alert(`当前用户没有权限发表回答！`);
            return;
        }
        if (!question) {
            parent.layui.layer.alert(`当前问题加载失败，请刷新重试！`);
            return;
        }
        parent.layer.open({
            title: "新增回答",
            type: 2,
            // area: ['48rem', '36rem'],
            area: ['80%', '80%'],
            content: `/answer-edit?question-id=${question.id}`,
            // title: false, // 不显示标题栏
            closeBtn: 1,
            fixed: true, // 固定
            // resize: false, // 不允许调整大小
            maxmin: true,
            shadeClose: true,
            shade: [0.1, '#16baaa'], // 遮罩
            anim: "slideDown" // 动画 从上边缘往下
        });
    });
}

document.addEventListener('DOMContentLoaded', () => {
    // 删除问题
    document.getElementById("answer-delete").addEventListener('click', function () {

        if (!user) {
            parent.layui.layer.alert(`当前您未登录，登陆后才能删除问题！`);
            return;
        }
        if (user.role !== "ASKER" && user.role !== "ADMIN") {
            parent.layui.layer.alert(`当前用户没有权限删除问题！`);
            return;
        }
        if (!question) {
            parent.layui.layer.alert(`问题未加载！`);
        }
        if (user.role !== "ADMIN" && question.userId !== user.id) {
            parent.layui.layer.alert(`您无权删除他人问题！`);
            return;
        }
        parent.layer.confirm(`确定删除问题(questionId:${question.id})吗？`, {
            btn: ['确定', '取消'],
            btnAlign: 'c', // 按钮居中显示
            btn1: function(){
                // 删除
                fetch(`/api/question/${question.id}`, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                    .then(response => {
                        if (!response.ok) {
                            parent.layui.layer.alert(`删除问题出错！<br />状态码：${response.status}`);
                            return;
                        }
                        parent.layer.msg(`删除问题成功！`);
                        // 刷新页面
                        parent.changeURLStatic('id', null);
                        parent.location.reload();
                    })
                    .catch(error => {
                        parent.layui.layer.msg('因网络原因，删除回答失败！');
                        console.error('Error:', error);
                    });
            }
        })
    });
    // 修改问题
    document.getElementById("answer-edit").addEventListener('click', function () {
        if (!user) {
            parent.layui.layer.alert(`当前您未登录，登陆后才能修改问题！`);
            return;
        }
        if (user.role !== "ASKER" && user.role !== "ADMIN") {
            parent.layui.layer.alert(`当前用户没有修改问题！`);
            return;
        }
        if (!question) {
            parent.layui.layer.alert(`问题未加载！`);
            return;
        }
        if (user.role !== "ADMIN" && question.userId !== user.id) {
            parent.layui.layer.alert(`您无权修改他人问题！`);
            return;
        }
        parent.layer.open({
            type: 2,
            title: '修改问题',
            content: `/question-edit?question-id=${question.id}`,
            area: ['80%', '80%'],
            // title: false, // 不显示标题栏
            closeBtn: 1,
            fixed: true, // 固定
            // resize: false, // 不允许调整大小
            shadeClose: true,
            shade: [0.1, '#16baaa'], // 遮罩
            anim: "slideDown" // 动画从上边缘往下
        });
    });
    layui.use(async function () {
        await initUser();
        await initQuestion();
        if (question) {
            answerTemplate = document.getElementById("answer-template").innerHTML;
            await initAnswer(question.id);
            initAnswerAdd();
        }

    });
});

function showOption(answerArrayIndex) {
    let answer = answerArray[answerArrayIndex];
    parent.layui.layer.alert(`请选择操作(answerId:${answer.id})`, {
        btn: ['删除', '修改', '取消'],
        btnAlign: 'c', // 按钮居中显示
        btn1: function(){
            // 删除
            if (!user) {
                parent.layui.layer.alert(`当前您未登录，登陆后才能删除回答！`);
                return;
            }
            if (user.role !== "RESPONDER" && user.role !== "ADMIN") {
                parent.layui.layer.alert(`当前用户没有权限删除回答！`);
                return;
            }
            if (user.role !== "ADMIN" && answer.userId !== user.id) {
                parent.layui.layer.alert(`您无权删除他人回答！`);
                return;
            }
            parent.layer.confirm(`确定删除回答(answerId:${answer.id})吗？`, {
                btn: ['确定', '取消'],
                btnAlign: 'c', // 按钮居中显示
                btn1: function(){
                    // 删除
                    fetch(`/api/answer/${answer.id}`, {
                        method: 'DELETE',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    })
                        .then(response => {
                            if (!response.ok) {
                                parent.layui.layer.alert(`删除回答出错！<br />状态码：${response.status}`);
                                return;
                            }
                            parent.layer.msg(`删除回答成功！`);
                            initAnswer(question.id);
                        })
                        .catch(error => {
                            parent.layui.layer.msg('因网络原因，删除回答失败！');
                            console.error('Error:', error);
                        });
                }
            })
        },
        btn2: function(){
            // 编辑
            if (!user) {
                parent.layui.layer.alert(`当前您未登录，登陆后才能修改回答！`);
                return;
            }
            if (user.role !== "RESPONDER" && user.role !== "ADMIN") {
                parent.layui.layer.alert(`当前用户没有权限修改回答！`);
                return;
            }
            if (user.role !== "ADMIN" && answer.userId !== user.id) {
                parent.layui.layer.alert(`您无权修改他人回答！`);
                return;
            }
            parent.layer.open({
                title: `修改回答(answerId:${answer.id})`,
                type: 2,
                // area: ['48rem', '36rem'],
                area: ['80%', '80%'],
                content: `/answer-edit?question-id=${question.id}&answer-id=${answer.id}`,
                // title: false, // 不显示标题栏
                closeBtn: 1,
                fixed: true, // 固定
                // resize: false, // 不允许调整大小
                maxmin: true,
                shadeClose: true,
                shade: [0.1, '#16baaa'], // 遮罩
                anim: "slideDown" // 动画 从上边缘往下
            });
        }
    });
}